<template>
  <div class="supplier-info">
    <h1 class="page-title">供应商信息页面</h1>
    <!-- 搜索区域 -->
    <div class="filter-bar">
      <el-input
        v-model="filterForm.keyword"
        placeholder="请输入供应商ID或名称(支持模糊查询)"
        clearable
        style="width: 300px; margin-right: 10px;"
        @keyup.enter="handleSearch"
        @clear="handleSearch"
      />
      <el-button type="primary" @click="handleSearch" icon="el-icon-search">查询</el-button>
      <el-button @click="resetFilter" icon="el-icon-refresh" style="margin-left: 10px;">重置</el-button>
      <!-- 新增新增按钮 -->
      <el-button type="success" @click="handleAdd" icon="el-icon-plus" style="margin-left: 10px;">新增</el-button>
    </div>
    <div class="table-container">
      <el-table :data="supplierList" style="width: 100%" border v-loading="loading">
        <el-table-column prop="id" label="供应商ID" width="120" />
        <el-table-column prop="supplierName" label="供应商名称" width="150" />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column prop="address" label="地址" width="150"/>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
         <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">


            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleEdit(scope.row)"
            >
              修改
            </el-button>

            <el-button
              size="small"
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="toggleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteSupplier(scope.row)"
              :disabled="scope.row.status === 2"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handlePageChange"
        :current-page="pagination.pageNo"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        style="margin-top: 20px;"
      />
    </div>
    <!-- 修改弹窗 -->
    <el-dialog
      :title="form.id ? '修改供应商信息' : '新增供应商信息'"
      v-model="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="form"
        ref="form"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="form.supplierName"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" type="textarea"></el-input>
        </el-form-item>
        <!-- 只在修改时显示状态选项 -->
        <el-form-item label="状态" v-if="form.id">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// 确保引入了所有需要的API函数
import { getSupplierListAPI, getSupplierByIdAPI, updateSupplierStatusAPI, deleteSupplierAPI, updateSupplierAPI, addSupplierAPI } from '@/apis/supplier'
import dayjs from 'dayjs'
export default {
  name: 'SupplierInfo',
  data() {
    return {
      // 弹窗相关
      dialogVisible: false,
      form: {
        id: null,
        supplierName: '',
        phone: '',
        address: '',
        status: 1
      },
      rules: {
        supplierName: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }]
      },
      // 列表数据
      supplierList: [],
      pagination: {
        pageNo: 1,
        pageSize: 10,
        total: 0
      },
      loading: false,
      // 搜索表单（统一使用filterForm）
      filterForm: {
        keyword: ''
      }
    }
  },
  created() {
    this.fetchSupplierList()
  },
  methods: {
    // 查询方法 - 智能判断是ID查询还是名称查询
    async handleSearch() {
      this.pagination.pageNo = 1

      // 如果有输入内容，判断是ID查询还是名称查询
      if (this.filterForm.keyword && this.filterForm.keyword.trim()) {
        const keyword = this.filterForm.keyword.trim();

        // 如果输入的是纯数字，优先按ID精确查询
        if (/^\d+$/.test(keyword)) {
          await this.searchById(parseInt(keyword));
        } else {
          // 否则按名称模糊查询
          await this.fetchSupplierList();
        }
      } else {
        // 如果没有输入内容，获取所有供应商
        await this.fetchSupplierList();
      }
    },

    // 重置筛选
    resetFilter() {
      this.filterForm = { keyword: '' }
      this.handleSearch()
    },

    // 格式化时间显示
    formatDateTime(date) {
      if (!date) return ''
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    },

    // 获取列表数据
    async fetchSupplierList() {
      this.loading = true
      try {
        const params = {
          pageNo: this.pagination.pageNo,
          pageSize: this.pagination.pageSize,
          keyword: this.filterForm.keyword.trim() || undefined // 只有非空时才传递keyword
        }
        const res = await getSupplierListAPI(params)
        this.supplierList = res.data?.records || []
        this.pagination.total = res.data?.total || 0
      } catch (error) {
        console.error('获取供应商列表失败:', error)
        this.$message.error(error.data?.msg || '获取供应商列表失败')
        this.supplierList = []
      } finally {
        this.loading = false
      }
    },

    // 通过ID精确查找的方法
    async searchById(id) {
      try {
        this.loading = true;
        const res = await getSupplierByIdAPI(id);

        if (res.data) {
          // 将单个结果转换为列表格式以适配现有表格
          this.supplierList = [res.data];
          this.pagination.total = 1;
          this.$message.success('查找成功');
        } else {
          this.supplierList = [];
          this.pagination.total = 0;
          this.$message.warning('未找到指定ID的供应商');
        }
      } catch (error) {
        console.error('获取供应商信息失败:', error);
        this.$message.error(error.data?.msg || '获取供应商信息失败');
        this.supplierList = [];
        this.pagination.total = 0;
      } finally {
        this.loading = false;
      }
    },

    // 新增供应商
    handleAdd() {
      this.form = {
        id: null,
        supplierName: '',
        phone: '',
        address: '',
        status: 1
      }
      this.dialogVisible = true
    },

    // 打开修改弹窗
    handleEdit(row) {
      // 深拷贝行数据，避免直接修改表格数据
      this.form = { ...row }
      this.dialogVisible = true
    },

    // 提交表单（新增或修改）
    async submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true
            if (this.form.id) {
              // 修改供应商
              const updateData = {
                id: this.form.id,
                supplierName: this.form.supplierName,
                phone: this.form.phone,
                address: this.form.address,
                status: this.form.status
              }
              await updateSupplierAPI(updateData)
              this.$message.success('修改成功')
            } else {
              // 新增供应商
              const addData = {
                supplierName: this.form.supplierName,
                phone: this.form.phone,
                address: this.form.address
              }
              await addSupplierAPI(addData)
              this.$message.success('新增成功')
            }
            this.dialogVisible = false
            await this.handleSearch() // 重新加载数据确保同步
          } catch (error) {
            console.error('操作失败:', error)
            this.$message.error(error.data?.msg || '操作失败')
          } finally {
            this.loading = false
          }
        }
      })
    },

    // 分页处理
    handlePageChange(pageNo) {
      this.pagination.pageNo = pageNo
      this.fetchSupplierList()
    },

    handlePageSizeChange(pageSize) {
      this.pagination.pageSize = pageSize
      this.pagination.pageNo = 1
      this.fetchSupplierList()
    },

    // 状态样式
    getStatusType(status) {
      switch (status) {
        case 0: return 'danger'
        case 1: return 'success'
        case 2: return 'info'
        default: return 'warning'
      }
    },

    // 状态文本
    getStatusText(status) {
      switch (status) {
        case 0: return '禁用'
        case 1: return '启用'
        case 2: return '已删除'
        default: return '未知状态'
      }
    },

    // 切换状态
    async toggleStatus(row) {
      if (this.loading) return
      try {
        const newStatus = row.status === 1 ? 0 : 1
        this.loading = true
        await updateSupplierStatusAPI({ id: row.id, status: newStatus })
        row.status = newStatus
        row.updateTime = new Date().toLocaleString()
        this.$message.success(`${newStatus === 1 ? '启用' : '禁用'}成功`)
      } catch (error) {
        console.error('更新状态失败:', error)
        this.$message.error(error.data?.msg || '更新状态失败')
      } finally {
        this.loading = false
      }
    },

    // 删除供应商
    async deleteSupplier(row) {
      if (row.status === 2) {
        this.$message.warning('该供应商已处于删除状态')
        return
      }

      this.$confirm('此操作将删除该供应商，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'

      }).then(async () => {
        if (this.loading) return
        try {
          this.loading = true
          // 1. 调用后端删除接口（软删除）
          await deleteSupplierAPI({ id: row.id })

          // 2. 关键修改：重新请求列表，利用后端逻辑过滤已删除数据
          await this.handleSearch()

          this.$message.success('删除成功!')
        } catch (error) {
          console.error('删除失败:', error)
          this.$message.error(error.data?.msg || '删除失败')
        } finally {
          this.loading = false
        }

      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.supplier-info {
  padding: 20px;
  background-color: #f5f5f5;
  text-align: center;
}

.page-title {
  font-size: 2.2rem;
  color: #2c3e50;
  margin: 20px 0;
  text-align: center;
  font-weight: bold;
}

.filter-bar {
  background-color: white;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.table-container {
  margin-top: 20px;
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  text-align: left;
}

@media (max-width: 768px) {
  .page-title {
    font-size: 1.8rem;
  }
  
  .filter-bar {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>
